import { Component, OnInit } from '@angular/core';
import * as _ from 'lodash';
import { FetchService } from '../../../../core/net/fetch.service';
import { NzMessageService } from 'ng-zorro-antd';

@Component({
    selector: 'app-ywglxt-tab1',
    templateUrl: './ywglxt-tab1.component.html',
    styleUrls: ['./ywglxt-tab1.component.scss']
})
export class YwglxtTab1Component implements OnInit {
    today = new Date();
    webBusTableDatas = [];
    editWebBusCache: { [key: string]: { edit: boolean; data: any } } = {};

    constructor(private message: NzMessageService,
                private fetchService: FetchService) {
    }

    ngOnInit(): void {
        this.queryInfo();
    }

    queryInfo(): void {
        this.fetchService.post('web/publish/list', {}).subscribe(res => {
            this.getWebBusData(res['wrsPublishBusDatas']);
        });
    }
    getWebBusData(list) {
        const thirdLen = Math.ceil(list.length / 3);
        const firstData = _.slice(list, 0, thirdLen);
        const secondData = _.slice(list, thirdLen, 2 * thirdLen);
        const thirdData = _.slice(list, 2 * thirdLen);
        this.webBusTableDatas = [firstData, secondData, thirdData];
        this.updateWebBusEditCache();
    }

    startWebBusEdit(id): void {
        this.editWebBusCache[id].edit = true;
    }

    updateWebBusEditCache(): void {
        const listOfData = _.flatten(this.webBusTableDatas);
        listOfData.forEach(item => {
            this.editWebBusCache[item.sideId] = {
                edit: false,
                data: {...item}
            };
        });
    }

    saveWebBusEdit(id: string): void {
        const listOfData = _.flatten(this.webBusTableDatas);
        const index = listOfData.findIndex(item => item.sideId === id);
        Object.assign(listOfData[index], this.editWebBusCache[id].data);
        this.editWebBusCache[id].edit = false;
        const thirdLen = Math.ceil(listOfData.length / 3);
        const firstData = _.slice(listOfData, 0, thirdLen);
        const secondData = _.slice(listOfData, thirdLen, 2 * thirdLen);
        const thirdData = _.slice(listOfData, 2 * thirdLen);
        this.webBusTableDatas = [firstData, secondData, thirdData];
    }

    cancelWebBusEdit(id): void {
        const listOfData = _.flatten(this.webBusTableDatas);
        const index = listOfData.findIndex(item => item.sideId === id);
        this.editWebBusCache[id] = {
            data: {...listOfData[index]},
            edit: false
        };
    }

    confirm(): void {
        const params = {
            wrsPublishBusDatas: _.flatten(this.webBusTableDatas)
        };
        this.fetchService.post('web/publish/add', params).subscribe(res => {
            this.message.success('提交成功');
            this.reset();
        });
    }

    reset(): void {
        this.fetchService.post('web/publish/list', {}).subscribe(res => {
            this.getWebBusData(res['wrsPublishBusDatas']);
        });
    }
}
